package com.zenithmind.coding.config;

import com.zenithmind.coding.config.security.SecurityConfigurationStrategy;
import com.zenithmind.coding.config.security.SecurityEndpointRegistry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

import java.util.List;

/**
 * 在线编程服务安全配置 - 遵循依赖倒置原则和策略模式
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class CodingSecurityConfig {

    private final SecurityEndpointRegistry endpointRegistry;
    private final List<SecurityConfigurationStrategy> configurationStrategies;



    /**
     * 在线编程服务安全配置 - 使用策略模式，支持动态配置
     */
    @Bean
    public SecurityFilterChain codingSecurityFilterChain(HttpSecurity http) throws Exception {
        log.info("开始配置在线编程服务安全过滤器链");

        // 按优先级排序配置策略
        configurationStrategies.stream()
                .sorted((s1, s2) -> Integer.compare(s1.getPriority(), s2.getPriority()))
                .forEach(strategy -> {
                    try {
                        log.debug("应用安全配置策略: {}", strategy.getStrategyName());
                        strategy.configure(http, endpointRegistry);
                    } catch (Exception e) {
                        log.error("应用安全配置策略 {} 失败", strategy.getStrategyName(), e);
                        throw new RuntimeException("安全配置失败", e);
                    }
                });

        log.info("在线编程服务安全过滤器链配置完成");
        return http.build();
    }

}
